import { YYYY_MM_DD } from './../utils/utils';
import { File } from './../entitys/File';
import { Service } from "typedi";
import { createWriteStream, existsSync, mkdirSync } from 'fs'
import { Multer } from 'multer';
import { join, resolve } from 'path'
import * as moment from 'moment';
import { getRepository } from 'typeorm';
@Service()
export default class FileService {
    static uploadFolder: string = "/public/uploads/"
    static filePathPrefix: string = "/uploads"
    async saveFile(files: any[]) {
        const fileModels = []
        for (let i = 0; i < files.length; i++) {
            const file = files[i]
            const { fileName, path } = await this.writeFile(file)
            const fileModel = new File()
            fileModel.name = fileName
            fileModel.fileName = file.originalname
            fileModel.path = path
            fileModel.updateTime = new Date()
            fileModel.createTime = new Date()
            fileModels.push(fileModel)
        }
        const fileRepository = getRepository(File)
        await fileRepository.save(fileModels)
        return fileModels
    }
    async writeFile(file: any) {
        const dateFolder = moment().format(YYYY_MM_DD)
        const folder = join(__dirname, '../../', FileService.uploadFolder, "./" + dateFolder)
        if (!existsSync(folder)) {
            mkdirSync(folder)
        }
        const originalname = (file.originalname as string)
        const fileName = Date.now() + originalname.substring(originalname.lastIndexOf("."))
        await new Promise((resolve, reject) => {
            const ws = createWriteStream(folder + "/" + fileName)
            ws.write(file.buffer, (err) => {
                ws.close();
                if (err) {
                    reject(err)
                    return
                }
                resolve("ok")
            })
            ws.end()
        })
        return {
            fileName,
            path: resolve(FileService.filePathPrefix, dateFolder, fileName)
        }
    }

}